package net.versiforma.libraryreminder.librarycontrollers;


import java.util.ArrayList;

import net.versiforma.libraryreminder.BorrowedItem;
import net.versiforma.libraryreminder.LibraryAccount;

import com.thoughtworks.selenium.DefaultSelenium;


public class StabiController implements LibraryInterface {

	public DefaultSelenium selenium;
	private LibraryAccount account;
	private static final String HOMEPAGE_URL = "https://ausleihe.staatsbibliothek-berlin.de";
	
	public StabiController(LibraryAccount account) {
		this.account = account;
		selenium = new DefaultSelenium("localhost", 4567, "*firefox", HOMEPAGE_URL);
	}
	
	
	public void start() {
		selenium.start();
		selenium.open("/opac/de/login_frm.html.S");
//		selenium.setSpeed("1000");
	}

	
	String usernameFieldLocator = "BENUTZER";
	String passwordFieldLocator = "PASSWORD";
	public void login() {
		selenium.selectFrame("name=MainFrame");
		selenium.type(usernameFieldLocator, account.getUserid());
		selenium.type(passwordFieldLocator, account.getPassword());
		selenium.click("//img[@title='Anmelden']");
		if (!selenium.isAlertPresent())
			selenium.waitForPageToLoad("30000");
	}
	
	
	public boolean loginFailedPageShown() {
		if (
				selenium.isTextPresent("Ausweisnummer oder Passwort sind falsch") || 
				selenium.isAlertPresent()
		) return true;
		else return false;
	}
	
	
	// TODO: check the proven text whether works
	public boolean noBorrowedItems() {
		if (selenium.isTextPresent("Sie haben keine Medien ausgeliehen."))
			return true;
		return false;
	}
	
	
	public ArrayList<BorrowedItem> getBorrowedItems() {

		String DATE_FORMAT = "dd.MM.yyyy";
		String TABLE_XPATH_LOCATOR = "//form[@action='/opac/verl.S']/table";
		ArrayList<BorrowedItem> borrowedItems = new ArrayList<BorrowedItem>();

		// Count borrowed items on shown page	
		int items_counter = selenium.getXpathCount(TABLE_XPATH_LOCATOR + "/tbody/tr").intValue();
		
		// Intentionally fail
		if (items_counter < 1) org.junit.Assert.fail("Target table has 0 rows, which probably mean it's a wrong table");

		// Collect data about the borrowed items
		for (int i=2; i<=items_counter; i++) {
			BorrowedItem item = new BorrowedItem();
			borrowedItems.add(item);
			item.setDueDate(selenium.getText(TABLE_XPATH_LOCATOR + "/tbody/tr["+i+"]/td[2]").trim(), DATE_FORMAT);
			item.setLibrary(selenium.getText(TABLE_XPATH_LOCATOR + "/tbody/tr["+i+"]/td[7]").trim());
			item.setTitle(selenium.getText(TABLE_XPATH_LOCATOR + "/tbody/tr["+i+"]/td[5]").trim());
		}
		
		return borrowedItems;
	}


	public void logout() {
		selenium.selectWindow("name=LeftFrame");
		selenium.click("//a[@href='javascript:start();']");
	}
	
	public void close() {
		selenium.stop();
	}


	public boolean maintenancePageShown() {
		// TODO Auto-generated method stub
		return false;
	}

}
